<?php

namespace app\h5api\controller;

// 公共类
use Firebase\JWT\JWT as JWTUtil;
use think\Controller;
use think\facade\Config;
use think\facade\Request;
use \app\common\model\User;

class Base extends Controller
{
    public $_userid = 0;
    public $limit = 10;
    public $lon = '';
    public $lat = '';
    public $_userInfo = [];
    public $is_show_module = true;

    public function __construct()
    {
//		echo $this->createjwt(['time'=>time(),'user_id'=>323,'nick_name'=>111,'type'=>'online']);die;
        parent::__construct();
        $this->limit = input('limit',10);
        $this->lon = input('lon','');
        $this->lat = input('lat','');
		$this->checkToken();
    }

	protected function checkToken()
	{
		$controller = Request()->controller(); //获取控制器名
		$action = Request()->action(); //获取方法名
		$path = $controller.'/'.$action;
		//获取不需要token的页面数组
		$excepts = config::pull('NoTokenApi');
		//循环判断本页面是否需要在这个数组里面
		$isExcept = in_array(strtolower($path),$excepts);
		if (!$isExcept){
			$this->verifyJwt();
		}
	}

    /**
     * 验证token
     * &#64;return \think\response\Json
     */
    public function verifyJwt()
    {
        $token = Request::instance()->header('token');
        if(!$token){
            throw new \think\exception\HttpException(-2, 'token error');
        }
        $key = md5(config::get('token.key')); //jwt的签发密钥，验证token的时候需要用到
        $data = [
            'is_show_module'=>$this->is_show_module,
        ];
        try{
            $jwtAuth = json_encode(JWTUtil::decode($token,$key,['HS256']));
            $authInfo = json_decode($jwtAuth,true);
            if(empty($authInfo['exp']) || $authInfo['exp'] < time()){
//                throw new \think\exception\HttpException(-2, '登录过期');
                $this->result($data,-2,'登录过期');
            }
            if (empty($authInfo['user_id'])){
//                throw new \think\exception\HttpException(-2, 'user error');
                $this->result($data,-2,'user error');
            }
            $userModel = new User();
            $user = $userModel->field('*')->where(['user_id'=>$authInfo['user_id']])->find();
            if(!$user){
//                throw new \think\exception\HttpException(-2, 'user error');
                $this->result($data,-2,'user error');
            }
        }catch (\Exception $e){
//            throw new \think\exception\HttpException(-2, $e->getMessage());
            $this->result($data,-2,$e->getMessage());
        }

        $this->_userid = $authInfo['user_id'];
        $this->_userInfo = $user->toArray();

    }

    // 返回身份数据
    function GetUserInfo()
    {
//        $UserModel = new \app\common\model\User();
//    $user = $UserModel->field('*')->where(['user_id'=>$this->_userid])->find();
//        if(!empty($user)){
//            $user = $user->toArray();
//        }
        return $this->_userInfo;
    }
}
